import re
import logging

from google.appengine.ext import db

BUCKETS = unicode('''acai berry
acini de pepe
aero chocolate bar
agar agar
almonds
aloo gobi
alphabits cereal
anchovies
iced doughnut
angel food cake
angel hair pasta
animal crackers
apple
applejacks
apple jacks
applesauce
apricot
artichokes
asiago cheese
asparagus
aubergine
avocado
bacon
bacon bits
bagel
bakers chocolate
baklava
balsamic dressing
banana
banana bread
barbecue
barley
basil
basmati rice
bbq
bean salad
bean sprouts
beans
beef
beef patty
beef pattie
beef patties
beets
birds nest cookies
birds nest soup
biscuit
biscuits
black bean buns
black eyed peas
black forest cake
blackberry
blueberry
blueberry muffins
bok choy
bologna
borscht
boysenberry
brains
bread
breadfruit
broccoli
brownie
bruschetta
brussel sprouts
buffalo meat
buffalo wings
bulgur
bun
bundt cake
burger
burgerking
burger king
burrito
butter
butter chicken
butter squash
cabbage
cabbage rolls
caesar salad
caflib
cake
california dressing
candy
candy cane
cannoli
cantaloupe
caramel
carrot cake
carrots
cashews
cassava
casserole
cauliflower
caviar
celery
cereal
chalupas
chamomile tea
chapatis
cheddar
cheerios
cheese
cheeseburger
cheesecake
cheesesteak
cheetos
cherry
chex mix
chick peas
chicken
chili con carne
chinese food
chips
chocolate
chocolate chips
chocolate chip cookies
chop suey
chow mien noodles
chowder
chunky peanut butter
churros
chutney
cider
cilantro
cinnamon
clams
cobbler
cocoa
coconut
cod
coffee
coffee crisp
coleslaw
compote
cookies
corn
corn chips
cornflakes
corn flakes
corn fritters
cornbread
corn bread
corndog
coroneto
couscous
cows tongue
crab
crab cake
cracker
crackers
cranberries
cranberry sauce
crawfish
creamcheese
cream cheese
cream of mushroom
cream puff
creamsicle
crepe
croissants
croutons
creme brule
cucumber
cumquat
currants
curry
custard
custard
dahl soup
dairy
dandelion greens
danish
dark chocolate
dates
deviled eggs
dill
dill pickles
dimsum
dim sum
dingdong
dingdongs
ding dong
ding dongs
ditalini
dolmades
donut
donuts
doritos
dream whip
drumsticks
duck
durian
dutch apple pie
dutch cookies
echinacea
eclairs
edamame
eggnog
eggplant
eggroll
eggs benedict
elbow macaroni
elephant ears
enchiladas
endive
english muffin
escargot
escarole
eskimo pie
espresso
fajitas
falafal
fasolada soup
feta
fettuccine
fiddlestick greens
fig newton
fig newtons
figs
fish
flan
flap jacks
flapjacks
flax oil
flax seeds
flour
focaccia bread
fortune cookie
frankfurters
free range eggs
french fries
french toast
fricassee
fried pie
fried rice
frijoles
fritos
fritters
frosting
fruit
fruit pie
fruit salad
fruitcake
fudge
fudgicle
funnel cake
gailan
gala apples
garbonzo
garlic
garlic bread
gazpacho
gelatin
gelato
giblets
ginger
ginger ale
ginger beer
gingerbread
gizzards
goats milk
gooseberry
goulash
graham crackers
granola
grapefruit
grapes
grapeseed oil
gravy
green beans
green olives
green pepper
guacamole
guava
gumbo
gyoza
haggis
halibut
ham
hamburger
hash browns
hearts of palm
heinz ketchup
herbs
herrings
ho hos
hoagie
hog jowl
hollandaise
hominy
honey
honey bun
honeydew
horseradish
hot chocolate
hot dog
huckleberries
hummus
ice cream
iceberg lettuce
iced tea
icee
icing
icing sugar
imitation baco bits
imitation crab
impastata cheese
icy pole
indian curry
indian jujubee
indian pudding
infant formula
instant coffee
instant oatmeal
irish stew
ita palm
italian bread
italian dressing
jalapeno
jam
jamaican patties
jambalaya
jell-o
jelly
jerky
juice
jujubes
kale
kamut
ketchup
kidney beans
kielbasa
kit kat candy bar
kiwi
kix cereal
knorr soup
kohlrabi
kool-aid
kraft dinner
kraft dressing
kumquat
lamb
lasagna
leeks
legumes
lemon tarts
lemonade
lemons
lentils
lettuce
licorice
life cereal
lima bean
limes
linguine
little debbies snack cakes
liver
liverwurst
lobster
long john donuts
macaroni
mackerel
mahi-mahi
mango
mangos
manicotti
maple syrup
maraschino cherries
margarine
marmalade
marmite
mars bar
marshmallows
martimonial cake
masala
mashed potatoes
mayhaws
mayonnaise
mcdonalds
mcdonald's
meatloaf
meatzilla
melon
milk
millet
mince meat
minestrone
miso
moussaka
mousse
mozzarella
muffin
mushroom
mustard
naan bread
nachos
nalleys chips
neapolitan ice cream
necco wafers
nectarines
nerds candy
nesquik drink mix
nestles quik
nestles chocolate
neufatual cheese
noodles
nuggets
nuts
nutter-butter cookies
oat cakes
oatmeal
octopus
okra
old dutch chips
olives
omelet
onion
orange
oregano
oreo cookies
organic salad
orzo
ostrich eggs
ovaltine
ox tail
oysters
paella
pakora
pancake
pancetta
papaya
paprika
parmesan
parsley
parsnips
passionfruit
pasta
pastry
pate
pavlova
peaches
peanut
peanut butter
peanuts
pears
peas
pecans
peking duck
peppermint
pepperoni
peppers
perch
perogies
persimmons
pesto
pickles
pie
pilaf
pimentos
pine nuts
pineapple
pinto beans
pistachios
pita bread
pizza
pizza hut
plantain
plum
plum sauce
poi
polenta
pollock
pomegranate
popcorn
popsicles
pork
porridge
portabello mushrooms
potato
potato chips
potroast
potstickers
poutine
prawns
pretzels
protein bars
protein shakes
prunes
pudding
puffed wheat
pumpernickel
pumpkin
putanesca
quail
quaker oatmeal
quakes rice cakes
quesadilla
quiche
quick oats
quince
quinoa
quorn
radicchio
radish
raisins
ramen
raspberry
ratatouille
ravioli
red delicious
red lentils
refried beans
relish
reuben sandwich
rhubarb
ribs
rice
rice cake
rice crackers
rice paper
ricotta cheese
rigatoni
rissotto
ritz crackers
rocky road ice cream
roll-ups
rolls
romaine
romano cheese
rooibos
rootbeer float
rosehips
roti
rutabaga
rye bread
rye crisp
salad
salami
salmon
salsa
samosa
sandwich
sardines
sashimi
sasparilla
satsuma
satziki
sauce
sausage
scallop
scones
sesame oil
sesame seeds
shallot
shark fin soup
shells
shepherds pie
sherbet
shish kabob
shortbread
shortcake
shredded wheat
shrimp
skors bars
sloppy joes
slushies
smoothie shake
smores
snapper
snow peas
sorbet
souffle
soup
sour cream
souvlaki
soybean
soysauce
spaghetti
spam
spanish rice
spanokopita
spartan apples
spelt
spinach
spinach dip
split peas
spumoni
squash
squid
starburst
starfruit
steak
stew
stirfry
stoned wheat crackers
strawberry
string cheese
stromboli
stuffing
succotash
sundae
sunflower seeds
sushi
sweet and sour
sweet potato
swiss chard
swiss cheese
swordfish
tabasco pepper sauce
tabbouleh salad
taco
taco bell
taffy
tahini
tamale
tamarind
tangerine
tapioca
tarts
tater tots
tempeh
tempura
teriyaki
thighs
thimbleberry
thousand island salad dressing
toast
tofu
tomato
torte
tortellini
tortillas
tossed salad
tostitos
trifle
triscuits
truffle
tuna
tuna
turkey
turmeric
turnip
turtle
tv dinner
tv dinners
twinkie
twinkies
twizzlers
uglifruit
unpasteurized milk vegetables
upside down cake
upside-down cake
vakalolo
vanilla
veal
vegemite
vegetable soup
venison
vermicelli
vichyssoise
vidalia onion
vindaloo
vine leaves
vinegar
virgin oil
vol-au-vent
vomit fruit
wafers
waffles
waldorf salad
walleye fish
walnuts
wasabi
water
watercress
watermelon
wax bean
wheat bread
wild rice
wings
wonder bread
wontons
xigua
xmas cake
yaki soba
yam
yautia
yellow beans
yellow squash
yiyantes
yogurt
yolk
yorkshire pudding
yucca
zabaglione sauce
zander fish
ziti
zours
zucchini
zwieback bread''', "utf-8").split('\n')

PATTERN = re.compile(r'\b(%s)\b' % '|'.join(BUCKETS), re.IGNORECASE)

class Food(db.Model):
  name = db.StringProperty(required=True)
  last_summary = db.TextProperty(required=False)
  last_content = db.TextProperty(required=False)
  last_modified = db.DateTimeProperty(auto_now=True)
  counter = db.IntegerProperty(default=0)

def assign(summary, content):
  lower = content.lower()
  matches = PATTERN.findall(lower)
  if matches:
    for match in set(matches):
      logging.info('Entry assigned to \'%s\' bucket.' % match)
      query = Food.all()
      query.filter('name =', match)
      food = query.fetch(1)
      if not food:
        food = Food(name=match)
      elif type(food) == list:
        food = food[0]
      else:
        raise TypeError('Expected a list.')
      food.counter += 1
      food.last_summary = summary
      food.last_content = content
      food.put()
